package org.jeecg.modules.demo.ch.service.impl;

import org.jeecg.modules.demo.ch.entity.ChDailyRecord;
import org.jeecg.modules.demo.ch.entity.ChDailyRecordDetails;
import org.jeecg.modules.demo.ch.mapper.ChDailyRecordDetailsMapper;
import org.jeecg.modules.demo.ch.mapper.ChDailyRecordMapper;
import org.jeecg.modules.demo.ch.service.IChDailyRecordService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 每日记录
 * @Author: jeecg-boot
 * @Date:   2022-11-29
 * @Version: V1.0
 */
@Service
public class ChDailyRecordServiceImpl extends ServiceImpl<ChDailyRecordMapper, ChDailyRecord> implements IChDailyRecordService {

	@Autowired
	private ChDailyRecordMapper chDailyRecordMapper;
	@Autowired
	private ChDailyRecordDetailsMapper chDailyRecordDetailsMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(ChDailyRecord chDailyRecord, List<ChDailyRecordDetails> chDailyRecordDetailsList) {
		chDailyRecordMapper.insert(chDailyRecord);
		if(chDailyRecordDetailsList!=null && chDailyRecordDetailsList.size()>0) {
			for(ChDailyRecordDetails entity:chDailyRecordDetailsList) {
				//外键设置
				entity.setChDailyRecordId(chDailyRecord.getId());
				chDailyRecordDetailsMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(ChDailyRecord chDailyRecord,List<ChDailyRecordDetails> chDailyRecordDetailsList) {
		chDailyRecordMapper.updateById(chDailyRecord);
		
		//1.先删除子表数据
		chDailyRecordDetailsMapper.deleteByMainId(chDailyRecord.getId());
		
		//2.子表数据重新插入
		if(chDailyRecordDetailsList!=null && chDailyRecordDetailsList.size()>0) {
			for(ChDailyRecordDetails entity:chDailyRecordDetailsList) {
				//外键设置
				entity.setChDailyRecordId(chDailyRecord.getId());
				chDailyRecordDetailsMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		chDailyRecordDetailsMapper.deleteByMainId(id);
		chDailyRecordMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			chDailyRecordDetailsMapper.deleteByMainId(id.toString());
			chDailyRecordMapper.deleteById(id);
		}
	}
	
}
